import {Injectable} from '@angular/core';
import * as localForage from 'localforage';
import {DateTime} from 'luxon';

@Injectable({
  providedIn: 'root'
})
export class ApplocalforageService {

  constructor() {
    // 可以在这里配置localForage，例如设置driver
    /* localForage.config({
       name: 'myApp',
       storeName: 'my_store'
     });*/
  }

  async setItem(key: string, value: any): Promise<void> {
    await localForage.setItem(key, value);
  }

  async getItem<T>(key: string): Promise<T | null> {
    return await localForage.getItem<T>(key);
  }

  async removeItem(key: string): Promise<void> {
    await localForage.removeItem(key);
  }

  async clear(): Promise<void> {
    await localForage.clear();
  }

  async length(): Promise<number> {
    return await localForage.length();
  }

  async keys(): Promise<string[]> {
    return await localForage.keys();
  }


  async getLock(key: string, lockTimeOut: number): Promise<number | null> {
    const lock = await localForage.getItem<number>(key);
    if (lock) {
      //判断是否过期  没过期获取失败
      if (DateTime.now().toMillis() - lock < lockTimeOut) {
        console.log('获取lock失败', key, lock);
        return null;
      }
    }
    const number = DateTime.now().toMillis();
    //存入lock生效时间(当前时间戳毫秒)
    await localForage.setItem<number>(key, number);
    return number;
  }

  async delLock(key: string, lock: number): Promise<void> {
    const lockNow = await localForage.getItem<number>(key);
    if (lockNow && lockNow == lock) {
      //锁值相同 删除
      await localForage.removeItem(key);
    } else {
      console.error("delLock失败", key, lock, lockNow);
    }
  }

}
